package com.le.tester.javaThink.fifth.chapter24_ConcurrentProgramming;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * createTime：2021/8/23 17:42
 * description：构造器共享状态
 */
interface ShareArg {
    int get();
}

class UnSafe implements ShareArg {
    private int i = 0;

    @Override
    public int get() {
        return i++;
    }

}

class Safe implements ShareArg {
    private static AtomicInteger counter = new AtomicInteger();

    @Override
    public int get() {
        return counter.getAndIncrement();
    }
}

class SharedUser implements HasID {

    private final int id;

    SharedUser(ShareArg sa) {
        this.id = sa.get();
    }

    @Override
    public int getID() {
        return id;
    }
}


public class SharedConstructorArgument {
    public static void main(String[] args) {
        UnSafe unSafe = new UnSafe();
        IDChecker.test(() -> new SharedUser(unSafe));

        Safe safe = new Safe();
        IDChecker.test(() -> new SharedUser(safe));
    }
}
